const ModuleMap = require('../model/moduleMap')
const modulesData = require('../../modules')

function convertModuleMapKeyValue() {
  
  const moduleMap = {}
  let value = null
  
  Object.keys(ModuleMap).forEach(key => {
    value = ModuleMap[key]
    moduleMap[value] = key
  })
  
  return moduleMap
}

function getModuleENKeyMap() {
  
  const moduleMap = convertModuleMapKeyValue()
  
  const moduleKeyMap = {}
  
  let moduleKey = null
  
  for (let key in modulesData) {
    moduleKey = key.split('.')[0]
    
    if (!moduleKeyMap[moduleKey]) {
      moduleKeyMap[moduleKey] = []
    }
    
    moduleKeyMap[moduleKey].push(moduleMap[key] || key)
    
  }
  
  return moduleKeyMap
}

function getModulesOriginKeys(selectedCNKeys) {
  const moduleKeyMap = getModuleENKeyMap()
  const moduleMap = convertModuleMapKeyValue()
  const selectedKeys = selectedCNKeys.map(key => {
    let keys = key.split('->')
    key = keys[keys.length - 1].trim()
    return moduleMap[key]
  })
  
  const modulesKeysMap = {}
  let modulesKeys = []
  let entryKey = null
  let entrySplitKeys = []
  let isParent = false
  
  selectedKeys.filter(Boolean).forEach(key => {
    
    entrySplitKeys = key.split('.')
    isParent = entrySplitKeys.length === 1
    entryKey = entrySplitKeys[0]
    
    if (!modulesKeysMap[entryKey]) {
      modulesKeysMap[entryKey] = []
    }
    
    if (isParent) {
      modulesKeysMap[entryKey] = moduleKeyMap[entryKey]
    } else {
      modulesKeysMap[entryKey].push(key)
    }
    
  })
  
  Object.keys(modulesKeysMap).forEach(key => {
    let keys = modulesKeysMap[key]
    keys = [...new Set(keys)].sort()
    modulesKeys = modulesKeys.concat(keys)
  })
  
  return modulesKeys
}

module.exports = {
  getModulesOriginKeys
}